import { Button, Form, Select, Space } from '@douyinfe/semi-ui';
import { debounce, identity, isEqual, isNumber, pickBy } from 'lodash';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { IQueryParams } from '@/widgets/table-pagination';
import { usePageContext } from './context';
import { initialFilter } from './helper';
import { fetchDict } from '@/redux/dict/dict-api';

const UserFilter = () => {
  const { Option } = Form.Select;
  const [allGroup, setAllGroup] = useState<any[]>([]);

  const PageContext = usePageContext();
  const PageAction = useMemo(() => {
    return {
      addRecord: PageContext.addRecord,
      queryParams: PageContext.queryParams,
      setQueryParams: PageContext.setQueryParams,
    };
  }, [PageContext]);

  const applyFilter = useCallback(
    (values: any) => {
      const _queryParams: IQueryParams = {
        ...PageAction.queryParams,
        filter: { ...pickBy(values, identity), ...pickBy(values, isNumber) },
      };
      if (!isEqual(_queryParams, PageAction.queryParams)) {
        PageAction.setQueryParams({ ..._queryParams, pageNum: 1 });
      }
    },
    [PageAction.queryParams]
  );

  useEffect(() => {
    fetchDict({ pageNum: 1, pageSize: 999, dictionaryType: 'GROUP' }).then(
      (res) => {
        setAllGroup(res.data.content);
      }
    );
  }, []);

  return (
    <Form
      labelPosition='left'
      className='gap-2 items-start'
      validateFields={() => ''}
      layout='horizontal'
      initValues={initialFilter}
      // onValueChange={debounce((values, changedValue) => {
      //   applyFilter(values);
      // }, 350)}
      onSubmit={(values: any) => {
        applyFilter(values);
      }}
      onReset={() => applyFilter(initialFilter)}
    >
      <Form.Input
        label='姓名'
        field='name'
        trigger='blur'
        placeholder='姓名'
      ></Form.Input>
      <Form.Select
        label='产业集团'
        field='groupName'
        placeholder='请选择产业集团'
        trigger='blur'
        showClear
        className='w-[200px]'
      >
        {allGroup?.map((type: any, idx: any) => (
          <Form.Select.Option key={`type_${idx}`} value={type?.dictionaryKey}>
            {type?.dictionaryKey}
          </Form.Select.Option>
        ))}
      </Form.Select>
      <Form.Input
        label='公司'
        field='corporation'
        trigger='blur'
        placeholder='公司'
      ></Form.Input>

      <Button theme='solid' htmlType='submit'>
        搜索
      </Button>
      <Button htmlType='reset'>重置</Button>
    </Form>
  );
};

export default UserFilter;
